package me.sunpeng.design.prototype.deepclone;

import java.io.*;

/**
 * @author sp
 */
public class DeepProtoType implements Serializable, Cloneable {
    @Serial
    private static final long serialVersionUID = 6306009827678901963L;
    /**
     * String 属性
     */
    public String name;
    /**
     * 引用类型
     */
    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        super();
    }

    /**
     * 深拷贝-方式1使用clone方法
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep;
        //完成基本数据类型和字符串的克隆
        deep = super.clone();
        //对引用类型属性，进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = deepCloneableTarget.clone();
        return deepProtoType;
    }

    /**
     * 深拷贝-方式2 通过对象的序列化实现(推荐)
     */
    public Object deepClone() {
        //创建字节流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //当前这个对象以对象流的方式输出
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            //从流中读取对象
            return (DeepProtoType) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //关闭流
            try {
                if (bos != null) {
                    bos.close();
                }
                if (oos != null) {
                    oos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (ois != null) {
                    ois.close();
                }

            } catch (Exception e2) {
                e2.printStackTrace();
            }

        }

    }
}
